package com.baymax.test.scene.view;

import android.animation.ValueAnimator;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapShader;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.RadialGradient;
import android.graphics.Shader;
import android.util.AttributeSet;
import android.view.View;

public class RippleView extends View {
    private Paint mPaint;
    private Bitmap mBitmap;
    private BitmapShader mShader;
    private Matrix mShaderMatrix;
    private float mScale;

    public RippleView(Context context) {
        super(context);
        init();
    }

    public RippleView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    private void init() {
        mBitmap = createGradientBitmap();
        mShader = new BitmapShader(mBitmap, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP);
        mPaint = new Paint();
        mPaint.setShader(mShader);
        mShaderMatrix = new Matrix();
        mScale = 1f;
    }

    private Bitmap createGradientBitmap() {
        Bitmap bitmap = Bitmap.createBitmap(200, 200, Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(bitmap);
        Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
        paint.setShader(new RadialGradient(100, 100, 100,
                new int[]{0x4400FF00, 0x440000FF},
                null, Shader.TileMode.CLAMP));
        canvas.drawCircle(100, 100, 100, paint);
        return bitmap;
    }

    @Override
    protected void onDraw(Canvas canvas) {
        canvas.drawCircle(getWidth() / 2, getHeight() / 2, getWidth() / 2, mPaint);
    }

    public void startRippleAnimation() {
        ValueAnimator animator = ValueAnimator.ofFloat(1f, 2f);
        animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                mScale = (float) animation.getAnimatedValue();
                mShaderMatrix.setScale(mScale, mScale);
                mShader.setLocalMatrix(mShaderMatrix);
                invalidate();
            }
        });
        animator.setDuration(500);
        animator.start();
    }
}
